﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using System;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using System.Linq;
using System.Threading;
using TyMES.Communication;
using TyMES.Communication.Request;
using TyMES.Communication.Response;
using TyMES.Model;
using TyMES.Model.BaseInformation;
using TyMES.PassStationCommunication;
using static TyMES.Communication.FactoryAPIBase;
using TyMES.Model.Record;
using Microsoft.AspNetCore.Http.HttpResults;
using static TyMES.ResponseModel.PassStationResponse;
using DotLiquid.Util;
using MailKit.Search;
using static Aliyun.OSS.Model.InventoryConfigurationModel;
using TyMES.ViewModel.BaseInformation.MaterialVMs;
using TyMES.TemporaryClass;

namespace TyMES.Services
{
    public class OrderService
    {
        private readonly ILogger logger;
        private readonly IConfiguration configuration;
        private readonly HttpService httpService;
        //private readonly IServiceScope serviceScope;
        private readonly WTMContext context;
        private Timer _timer;
        private Order_Model _model;
        private ProductDataService _productDataService;
        private StationServices _stationServices;
        private string mesIP;
        private string mesPort;
        private string _LineCode;
        private string ordercode;

        public void StartUpdateTimer(TimeSpan interval)
        {
            _timer = new Timer(async state =>
            {
                //await UpdateOrderAsync(_LineCode); // 替换为实际的生产线编码
            }, null, interval, interval);
        }

        public void StopUpdateTimer()
        {
            _timer?.Dispose();
        }
        public void OrderhasChanged()
        { 
            _model=new Order_Model();
        }
        
        public OrderService(ILogger<OrderService> logger, WTMContext context,IConfiguration configuration, HttpService httpService, 
            ProductDataService productDataService,StationServices stationServices)
        {
            this.logger = logger;
            this.configuration = configuration;
            this.httpService = httpService;
            //this.serviceScope = serviceScopeFactory.CreateScope();
            //var sp = this.serviceScope.ServiceProvider;
            this.context = context;
            _model = new Order_Model();
            _productDataService = productDataService;
            _stationServices = stationServices;
            this.mesIP = configuration["MESIP"];
            this.mesPort = configuration["MESPORT"];
            this._LineCode = configuration["LineCode"];
        }

      


        public async Task<GetChildLine> GetLineCodeFromFMES(GetChildLineRequest request)
        {
            string factoryCode = configuration["FactoryCode"];
            string mesIP = configuration["MESIP"];
            string mesPort = configuration["MESPORT"];

            //利用工厂编码，产线编码 调用工单排程信息查询接口
            string url = "http://" + mesIP + ":" + mesPort + configuration["GETCHILDLINE"];
            string psd = System.Text.Json.JsonSerializer.Serialize(request);
            string value = await httpService.PostDataAsync(url, psd);
            try
            {
                //ApiResponse<GetChildLineResponse> response = JsonConvert.DeserializeObject<ApiResponse<GetChildLineResponse>>(value);
                
                GetChildLine response = System.Text.Json.JsonSerializer.Deserialize<GetChildLine>(value);

                return response;
            }
            catch(Exception ex)
            { return null; }
        }


        private ResponseBase Distrurb(GetChildLine response)
        {
            var length = response.Data.MaterialProperties.Count;
            for (int i = 0; i < length; i++)
            {
                if (response.Data.MaterialProperties[i].CustomProperty == "fddl_CXFD")
                {
                    var stationCode = response.Data.MaterialProperties[i].PropertyValue;
                    if (stationCode == "1")
                    {
                        return new ResponseBase(true, _LineCode+"-1");
                    }
                    else if (stationCode == "2")
                    {
                        return new ResponseBase(true, _LineCode + "-2");
                    }
                    else if (stationCode == "3")
                    {
                        return new ResponseBase(true, _LineCode + "-3");
                    }
                    else if (stationCode == "4")
                    {
                        return new ResponseBase(true, _LineCode + "-4");
                    }
                }
            }
            return new ResponseBase(false, "err");

        }

        // 调用工厂MES获取工单信息
        public async Task<ResponseBase> UpdateOrderAsync(string lineCode)
        {
            string factoryCode = configuration["FactoryCode"];
            string mesIP = configuration["MESIP"];
            string mesPort = configuration["MESPORT"];

            //利用工厂编码，产线编码 调用工单排程信息查询接口
            string url = "http://" + mesIP + ":" + mesPort + configuration["BASEURL"];
            

            ResquestBody resquestBody = new()
            {
                lineCode = lineCode,
                //orderCode = orderInfo.orderCode,
                factoryCode = factoryCode,
                serviceId = "Base003_OrderList"
            };

            try
            {
                string psd = JsonConvert.SerializeObject(resquestBody);
                string value = await httpService.PostDataAsync(url, psd);
                //string value = "{\"code\":\"000000\",\"data\":[{\"endTime\":\"2024-05-30 23:59:00\",\"equipmentCode\":\"\",\"factoryCode\":\"TH13\",\"field1\":\"\",\"field2\":\"\",\"field3\":\"\",\"field4\":\"\",\"field5\":\"\",\"lineCode\":\"DM-2-TY\",\"lineName\":\"DD-TY-DM-2#\",\"materialCode\":\"14599497-00\",\"materialId\":\"1765007000749121538\",\"materialName\":\"BPS15-2100070AE_EHS电混系统\",\"materialVersion\":\"A\",\"orderCode\":\"GD24052101\",\"orderQty\":\"500\",\"orderStatus\":\"35\",\"orderType\":\"QC02\",\"scheduleCode\":\"PC24052101\",\"scheduleEditTime\":\"\",\"scheduleId\":\"\",\"scheduleQty\":\"500\",\"scheduleStationId\":\"\",\"scheduleStatus\":\"2\",\"startTime\":\"2024-05-21 00:00:00\",\"stationCode\":\"2-OP4010\",\"stationName\":\"2-OP4010装油冷器密封圈、油冷器、打紧油冷器螺栓\",\"workshopCode\":\"No3_WS\",\"workshopName\":\"电动总成车间\"},{\"endTime\":\"2024-05-30 23:59:00\",\"equipmentCode\":\"\",\"factoryCode\":\"TH13\",\"field1\":\"\",\"field2\":\"\",\"field3\":\"\",\"field4\":\"\",\"field5\":\"\",\"lineCode\":\"DM-2-TY\",\"lineName\":\"DD-TY-DM-2#\",\"materialCode\":\"BSX-14599497\",\"materialId\":\"1776878157711237121\",\"materialName\":\"BSX-14599497虚拟变速器\",\"materialVersion\":\"A\",\"orderCode\":\"GD24052101C01\",\"orderQty\":\"500\",\"orderStatus\":\"35\",\"orderType\":\"QC02\",\"scheduleCode\":\"PC24052101C240521\",\"scheduleEditTime\":\"\",\"scheduleId\":\"\",\"scheduleQty\":\"500\",\"scheduleStationId\":\"\",\"scheduleStatus\":\"3\",\"startTime\":\"2024-05-21 00:00:00\",\"stationCode\":\"2-OP3010\",\"stationName\":\"2-OP3010后箱体上线\",\"workshopCode\":\"No3_WS\",\"workshopName\":\"电动总成车间\"},{\"endTime\":\"2024-05-30 23:59:00\",\"equipmentCode\":\"\",\"factoryCode\":\"TH13\",\"field1\":\"\",\"field2\":\"\",\"field3\":\"\",\"field4\":\"\",\"field5\":\"\",\"lineCode\":\"DM-2-TY\",\"lineName\":\"DD-TY-DM-2#\",\"materialCode\":\"QX-DEHS-1\",\"materialId\":\"1776882850976518146\",\"materialName\":\"QX-DEHS-1前箱虚拟物料\",\"materialVersion\":\"A\",\"orderCode\":\"GD24052101C01C02\",\"orderQty\":\"500\",\"orderStatus\":\"35\",\"orderType\":\"QC02\",\"scheduleCode\":\"PC24052101C240521C240521\",\"scheduleEditTime\":\"\",\"scheduleId\":\"\",\"scheduleQty\":\"500\",\"scheduleStationId\":\"\",\"scheduleStatus\":\"3\",\"startTime\":\"2024-05-21 00:00:00\",\"stationCode\":\"2-OP3020\",\"stationName\":\"2-OP3020前箱体上线\",\"workshopCode\":\"No3_WS\",\"workshopName\":\"电动总成车间\"},{\"endTime\":\"2024-05-30 23:59:00\",\"equipmentCode\":\"\",\"factoryCode\":\"TH13\",\"field1\":\"\",\"field2\":\"\",\"field3\":\"\",\"field4\":\"\",\"field5\":\"\",\"lineCode\":\"DM-2-TY\",\"lineName\":\"DD-TY-DM-2#\",\"materialCode\":\"ZX-DEHS-1-B\",\"materialId\":\"1780854372224507906\",\"materialName\":\"虚拟DEHS轴系小速比\",\"materialVersion\":\"A\",\"orderCode\":\"GD24052102\",\"orderQty\":\"500\",\"orderStatus\":\"35\",\"orderType\":\"QC02\",\"scheduleCode\":\"PC24052102\",\"scheduleEditTime\":\"\",\"scheduleId\":\"\",\"scheduleQty\":\"500\",\"scheduleStationId\":\"\",\"scheduleStatus\":\"2\",\"startTime\":\"2024-05-21 00:00:00\",\"stationCode\":\"2-OP030\",\"stationName\":\"2-OP030装发动机轴滚针轴承、定距环，各齿轴上线\",\"workshopCode\":\"No3_WS\",\"workshopName\":\"电动总成车间\"}],\"fail\":false,\"mesg\":\"处理成功\",\"success\":true,\"time\":\"2024-05-21T10:55:00.684Z\"}";
                OrderRes orderRes1= JsonConvert.DeserializeObject<OrderRes>(value);
                //每个分段只保留第一条工单信息

                var orderRes =await KeepFirstOrder(orderRes1);
                // 将新建工单新增产线MES
                // 根据获取的数据填入产线MES工单信息中
                for (int i = 0; i < orderRes.data.ToArray().Length; i++)
                {
                    Order_Model order = new Order_Model()
                    {
                        OrderCode = orderRes.data[i].orderCode,

                        MaterialCode = orderRes.data[i].materialCode,
                        MaterialVersion = orderRes.data[i].materialVersion,
                        OrderQty = orderRes.data[i].orderQty,
                        ScheduleCode = orderRes.data[i].scheduleCode,
                        ScheduleQty = orderRes.data[i].scheduleQty,
                        MaterialName = orderRes.data[i].materialName,
                        OrderType = orderRes.data[i].orderType,
                        MaterialId = orderRes.data[i].materialId,
                        ScheduleEditTime = orderRes.data[i].scheduleEditTime,
                        ScheduleId = orderRes.data[i].scheduleId,
                        ScheduleStationId = orderRes.data[i].scheduleStationId,

                        //排程状态（0-新建，1-下达，2-开线，3-生产，4-暂停，5-取消，6-完成）
                        MOrderStatus =  orderRes.data[i].ScheduleStatus,
                        WorkshopCode = orderRes.data[i].workshopCode,
                        WorkshopName = orderRes.data[i].workshopName,
                        LineCode = lineCode,
                        LineName = orderRes.data[i].lineName,
                        StationCode = orderRes.data[i].stationCode,
                        StationName = orderRes.data[i].stationName,
                        EquipmentCode = orderRes.data[i].equipmentCode,
                        StartTime = orderRes.data[i].startTime,
                        EndTime = orderRes.data[i].endTime,
                        FactoryCode = orderRes.data[i].factoryCode,
                        Field1 = orderRes.data[i].field1,
                        Field2 = orderRes.data[i].field2,
                        Field3 = orderRes.data[i].field3,
                        Field4 = "0",
                        // 保存工厂MES产线编码
                        Field5 = orderRes.data[i].lineCode
                    };

                    switch (orderRes.data[i].orderStatus)
                    {
                        case "5": //新建
                            order.Order_Status = OrderStatusEnum.CREATE;
                            break;
                        case "25": //部分排程
                            order.Order_Status = OrderStatusEnum.ISSUE;
                            break;
                        case "30": //已下达
                            order.Order_Status = OrderStatusEnum.ISSUE;
                            break;
                        case "35": //已排程
                            order.Order_Status = OrderStatusEnum.ISSUE;
                            break;
                        case "45": //完成
                            order.Order_Status = OrderStatusEnum.FINISH;
                            break;
                        case "55": //完结
                            order.Order_Status = OrderStatusEnum.STOP;
                            break;
                        case "65": //取消
                            order.Order_Status = OrderStatusEnum.CANCEL;
                            break;
                        default:
                            break;
                    }

                    //修改工单状态
                    //先利用工单编码查询本地是否存在
                    //存在该工单则修改工单信息
                    //不存在则新增工单信息
                    Order_Model TTTmOrder = context.DC.Set<Order_Model>().SingleOrDefault(x => x.OrderCode == orderRes.data[i].orderCode && x.ScheduleCode == orderRes.data[i].scheduleCode);


                    //创建工单
                    if (TTTmOrder == null)
                    {
                        //if (_model == null) _model = new Order_Model();
                        //if (_model.OrderCode != order.OrderCode && _model.ScheduleCode != order.ScheduleCode)
                        //{
                        //    GetChildLineRequest request =
                        //        new GetChildLineRequest(order.MaterialCode, order.MaterialVersion);
                        //    var res = await GetLineCodeFromFMES(request);
                        //    var res1 = Distrurb(res);
                        //    //ResponseBase res1 = GetLineCode(orderRes.data[i].field5, orderRes.data[i].stationCode);//用固定方式判断
                        //    //将旧工单排程状态置为2或6（非生产状态即可），新工单状态置为3
                        //    ChangeLastProduceOrderScheduleStatus(res1.Mesg);
                        //    order.LineCode = res1.Mesg;
                        //    order.MOrderStatus = "2";
                        //    this._model = TTTmOrder;
                        //}

                        GetChildLineRequest request =
                               new GetChildLineRequest(order.MaterialCode, order.MaterialVersion);
                        var res = await GetLineCodeFromFMES(request);
                        var res1 = Distrurb(res);
                        

                        //ResponseBase res1 = GetLineCode(orderRes.data[i].field5, orderRes.data[i].stationCode);//用固定方式判断
                        //将旧工单排程状态置为2或6（非生产状态即可），新工单状态置为3
                        ChangeLastProduceOrderScheduleStatus(res1.Mesg);
                        order.LineCode = res1.Mesg;
                        order.MOrderStatus = "3";


                        //同步排程状态至工厂mes
                        await SysncScheduleStatus(order);


                        this._model = TTTmOrder;
                        context.DC.Set<Order_Model>().Add(order);
                        await context.DC.SaveChangesAsync();
                        
                    }
                    else
                    {
                        //修改工单状态
                        if (TTTmOrder.MOrderStatus != order.MOrderStatus)
                        {

                            if(order.MOrderStatus=="3")
                                ChangeLastProduceOrderScheduleStatus(TTTmOrder.LineCode);
                            TTTmOrder.OrderCode = orderRes.data[i].orderCode;
                            TTTmOrder.MaterialCode = orderRes.data[i].materialCode;
                            TTTmOrder.MaterialVersion = orderRes.data[i].materialVersion;
                            TTTmOrder.OrderQty = orderRes.data[i].orderQty;
                            TTTmOrder.ScheduleCode = orderRes.data[i].scheduleCode;
                            TTTmOrder.ScheduleQty = orderRes.data[i].scheduleQty;
                            TTTmOrder.MaterialName = orderRes.data[i].materialName;
                            TTTmOrder.OrderType = orderRes.data[i].orderType;
                            TTTmOrder.MaterialId = orderRes.data[i].materialId;
                            TTTmOrder.ScheduleEditTime = orderRes.data[i].scheduleEditTime;
                            TTTmOrder.ScheduleId = orderRes.data[i].scheduleId;
                            TTTmOrder.ScheduleStationId = orderRes.data[i].scheduleStationId;

                            //排程状态（0-新建，1-下达，2-开线，3-生产，4-暂停，5-取消，6-完成）
                            TTTmOrder.MOrderStatus = orderRes.data[i].ScheduleStatus;
                            TTTmOrder.WorkshopCode = orderRes.data[i].workshopCode;
                            TTTmOrder.WorkshopName = orderRes.data[i].workshopName;
                            TTTmOrder.LineName = orderRes.data[i].lineName;
                            TTTmOrder.StationCode = orderRes.data[i].stationCode;
                            TTTmOrder.StationName = orderRes.data[i].stationName;
                            TTTmOrder.EquipmentCode = orderRes.data[i].equipmentCode;
                            TTTmOrder.StartTime = orderRes.data[i].startTime;
                            TTTmOrder.EndTime = orderRes.data[i].endTime;
                            TTTmOrder.FactoryCode = orderRes.data[i].factoryCode;
                            TTTmOrder.Field1 = orderRes.data[i].field1;
                            TTTmOrder.Field2 = orderRes.data[i].field2;
                            TTTmOrder.Field3 = orderRes.data[i].field3;
                            TTTmOrder.Field4 = "0";
                            // 保存工厂MES产线编码
                            TTTmOrder.Field5 = orderRes.data[i].lineCode;
                            TTTmOrder.MOrderStatus = order.MOrderStatus;
                            await context.DC.SaveChangesAsync();
                        }
                    }

                    await BOMSynchronousAsync(order.OrderCode, "TH13", lineCode);
                    await _productDataService.GetAllDataTemplate(order.MaterialCode, TTTmOrder==null?order.LineCode:TTTmOrder.LineCode, order);
                    //await _productDataService.GetAllDataTemplate(order.MaterialCode, lineCode, order.OrderCode);
                    /*
                    string bomsysinfo = await BOMSynchronousAsync(order.orderCode, factoryCode, orderInfo.lineCode);
                    if (bomsysinfo == "工单bom同步失败")
                    {
                        return new Response("000004", false, true, "同步工单信息成功, 工单bom同步失败", DateTime.Now.ToString("yy-MM-dd HH:mm:ss"));
                    }
                    */
                }
                //更新所有在生产工单产品BOM
                await UpdateProducingBomInfo();
                return new ResponseBase(true, "获取工单信息成功");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new ResponseBase(false, "获取工单信息失败");
            }
        }

        /// <summary>
        /// 此方法用于工厂mes推送
        /// </summary>
        /// <param name="fMOrderRes"></param>
        /// <returns></returns>
        public async Task<ResponseBase> FMUpdateOrderAsync(FMOrderRes fMOrderRes)
        {
            
            try
            {
                

                 OrderRes orderRes1 =await PackUpdateOrderInfo(fMOrderRes);

                var orderRes = await KeepFirstOrder(orderRes1);
                List<string> hasRecorded = new List<string>();
                // 将新建工单新增产线MES
                // 根据获取的数据填入产线MES工单信息中
                for (int i = 0; i < orderRes.data.ToArray().Length; i++)
                {
                    Order_Model order = new Order_Model()
                    {
                        OrderCode = orderRes.data[i].orderCode,

                        MaterialCode = orderRes.data[i].materialCode,
                        MaterialVersion = orderRes.data[i].materialVersion,
                        OrderQty = orderRes.data[i].orderQty,
                        ScheduleCode = orderRes.data[i].scheduleCode,
                        ScheduleQty = orderRes.data[i].scheduleQty,
                        MaterialName = orderRes.data[i].materialName,
                        OrderType = orderRes.data[i].orderType,
                        MaterialId = orderRes.data[i].materialId,
                        ScheduleEditTime = orderRes.data[i].scheduleEditTime,
                        ScheduleId = orderRes.data[i].scheduleId,
                        ScheduleStationId = orderRes.data[i].scheduleStationId,

                        //排程状态（0-新建，1-下达，2-开线，3-生产，4-暂停，5-取消，6-完成）
                        MOrderStatus = orderRes.data[i].ScheduleStatus,
                        WorkshopCode = orderRes.data[i].workshopCode,
                        WorkshopName = orderRes.data[i].workshopName,
                        LineCode = _LineCode,
                        LineName = orderRes.data[i].lineName,
                        StationCode = orderRes.data[i].stationCode,
                        StationName = orderRes.data[i].stationName,
                        EquipmentCode = orderRes.data[i].equipmentCode,
                        StartTime = orderRes.data[i].startTime,
                        EndTime = orderRes.data[i].endTime,
                        FactoryCode = orderRes.data[i].factoryCode,
                        Field1 = orderRes.data[i].field1,
                        Field2 = orderRes.data[i].field2,
                        Field3 = orderRes.data[i].field3,
                        Field4 = "0",
                        // 保存工厂MES产线编码
                        Field5 = orderRes.data[i].lineCode
                    };

                    switch (orderRes.data[i].orderStatus)
                    {
                        case "5": //新建
                            order.Order_Status = OrderStatusEnum.CREATE;
                            break;
                        case "25": //部分排程
                            order.Order_Status = OrderStatusEnum.ISSUE;
                            break;
                        case "30": //已下达
                            order.Order_Status = OrderStatusEnum.ISSUE;
                            break;
                        case "35": //已排程
                            order.Order_Status = OrderStatusEnum.ISSUE;
                            break;
                        case "45": //完成
                            order.Order_Status = OrderStatusEnum.FINISH;
                            break;
                        case "55": //完结
                            order.Order_Status = OrderStatusEnum.STOP;
                            break;
                        case "65": //取消
                            order.Order_Status = OrderStatusEnum.CANCEL;
                            break;
                        default:
                            break;
                    }

                    //修改工单状态
                    //先利用工单编码查询本地是否存在
                    //存在该工单则修改工单信息
                    //不存在则新增工单信息
                    Order_Model TTTmOrder = context.DC.Set<Order_Model>().SingleOrDefault(x => x.OrderCode == orderRes.data[i].orderCode && x.ScheduleCode == orderRes.data[i].scheduleCode);


                    //创建工单
                    if (TTTmOrder == null)
                    {
                        //if (_model == null) _model = new Order_Model();
                        //if (_model.OrderCode != order.OrderCode && _model.ScheduleCode != order.ScheduleCode)
                        //{
                        //    GetChildLineRequest request =
                        //        new GetChildLineRequest(order.MaterialCode, order.MaterialVersion);
                        //    var res = await GetLineCodeFromFMES(request);
                        //    var res1 = Distrurb(res);
                        //    //ResponseBase res1 = GetLineCode(orderRes.data[i].field5, orderRes.data[i].stationCode);//用固定方式判断
                        //    //将旧工单排程状态置为2或6（非生产状态即可），新工单状态置为3
                        //    ChangeLastProduceOrderScheduleStatus(res1.Mesg);
                        //    order.LineCode = res1.Mesg;
                        //    order.MOrderStatus = "2";
                        //    this._model = TTTmOrder;
                        //}

                        GetChildLineRequest request =
                               new GetChildLineRequest(order.MaterialCode, order.MaterialVersion);
                        var res = await GetLineCodeFromFMES(request);
                        var res1 = Distrurb(res);
                        //ResponseBase res1 = GetLineCode(orderRes.data[i].field5, orderRes.data[i].stationCode);//用固定方式判断
                        //将旧工单排程状态置为2或6（非生产状态即可），新工单状态置为3
                        ChangeLastProduceOrderScheduleStatus(res1.Mesg);
                        order.LineCode = res1.Mesg;
                        order.MOrderStatus = "3";


                        //同步排程状态至工厂mes
                        await SysncScheduleStatus(order);


                        this._model = TTTmOrder;
                        context.DC.Set<Order_Model>().Add(order);
                        await context.DC.SaveChangesAsync();

                    }
                    //修改工单状态
                    else
                    {
                        //修改工单状态
                        if (TTTmOrder.MOrderStatus != order.MOrderStatus)
                        {

                            if (order.MOrderStatus == "3")
                                ChangeLastProduceOrderScheduleStatus(TTTmOrder.LineCode);
                            TTTmOrder.OrderCode = orderRes.data[i].orderCode;
                            TTTmOrder.MaterialCode = orderRes.data[i].materialCode;
                            TTTmOrder.MaterialVersion = orderRes.data[i].materialVersion;
                            TTTmOrder.OrderQty = orderRes.data[i].orderQty;
                            TTTmOrder.ScheduleCode = orderRes.data[i].scheduleCode;
                            TTTmOrder.ScheduleQty = orderRes.data[i].scheduleQty;
                            TTTmOrder.MaterialName = orderRes.data[i].materialName;
                            TTTmOrder.OrderType = orderRes.data[i].orderType;
                            TTTmOrder.MaterialId = orderRes.data[i].materialId;
                            TTTmOrder.ScheduleEditTime = orderRes.data[i].scheduleEditTime;
                            TTTmOrder.ScheduleId = orderRes.data[i].scheduleId;
                            TTTmOrder.ScheduleStationId = orderRes.data[i].scheduleStationId;

                            //排程状态（0-新建，1-下达，2-开线，3-生产，4-暂停，5-取消，6-完成）
                            TTTmOrder.MOrderStatus = orderRes.data[i].ScheduleStatus;
                            TTTmOrder.WorkshopCode = orderRes.data[i].workshopCode;
                            TTTmOrder.WorkshopName = orderRes.data[i].workshopName;
                            TTTmOrder.LineName = orderRes.data[i].lineName;
                            TTTmOrder.StationCode = orderRes.data[i].stationCode;
                            TTTmOrder.StationName = orderRes.data[i].stationName;
                            TTTmOrder.EquipmentCode = orderRes.data[i].equipmentCode;
                            TTTmOrder.StartTime = orderRes.data[i].startTime;
                            TTTmOrder.EndTime = orderRes.data[i].endTime;
                            TTTmOrder.FactoryCode = orderRes.data[i].factoryCode;
                            TTTmOrder.Field1 = orderRes.data[i].field1;
                            TTTmOrder.Field2 = orderRes.data[i].field2;
                            TTTmOrder.Field3 = orderRes.data[i].field3;
                            TTTmOrder.Field4 = "0";
                            // 保存工厂MES产线编码
                            TTTmOrder.Field5 = orderRes.data[i].lineCode;
                            TTTmOrder.MOrderStatus = order.MOrderStatus;
                            await context.DC.SaveChangesAsync();
                        }
                    }

                    await BOMSynchronousAsync(order.OrderCode, "TH13", _LineCode);
                    await _productDataService.GetAllDataTemplate(order.MaterialCode, TTTmOrder == null ? order.LineCode : TTTmOrder.LineCode, order);
                    //await _productDataService.GetAllDataTemplate(order.MaterialCode, lineCode, order.OrderCode);
                    /*
                    string bomsysinfo = await BOMSynchronousAsync(order.orderCode, factoryCode, orderInfo.lineCode);
                    if (bomsysinfo == "工单bom同步失败")
                    {
                        return new Response("000004", false, true, "同步工单信息成功, 工单bom同步失败", DateTime.Now.ToString("yy-MM-dd HH:mm:ss"));
                    }
                    */
                }
                
                return new ResponseBase(true, "获取工单信息成功");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new ResponseBase(false, "获取工单信息失败");
            }
        }

        /// <summary>
        ///封装工厂mes下发工单信息
        /// </summary>
        /// <param name="fMOrderRes"></param>
        /// <returns></returns>
        public async Task<OrderRes> PackUpdateOrderInfo(FMOrderRes fMOrderRes)
        {
            List<OrderData> data = new List<OrderData>();
            foreach(var fmorder in fMOrderRes.data)
            {
                OrderData orderData = new OrderData(
                    fmorder.orderType,fmorder.orderCode,fmorder.orderQty,fmorder.orderStatus,fmorder.materialCode,
                    fmorder.materialId,fmorder.materialName,fmorder.materialVersion,fmorder.scheduleCode,fmorder.scheduleQty,
                    fmorder.scheduleEditTime,fmorder.scheduleId,"",fmorder.ScheduleStatus,fmorder.workshopCode,
                    fmorder.workshopName,fmorder.lineCode,fmorder.lineName,fmorder.stationCode,fmorder.stationName,"",
                    fmorder.startTime,fmorder.endTime,fmorder.factoryCode,"","","","","",fmorder.lineSubsectionCode,fmorder.lineSubsectionName);

                data.Add(orderData);
            }
            return new OrderRes("000000", data, true, false, "", "");
        }

        public async Task<OrderRes> KeepFirstOrder(OrderRes orderRes1)
        {
            var data = new List<OrderData>();
            List<string> lineSubsectionCode = new List<string>();
            foreach (var orderinfo in orderRes1.data)
            {
                if (lineSubsectionCode.Any(x => x == orderinfo.lineSubsectionCode)||orderinfo.lineSubsectionCode==""||orderinfo.lineSubsectionCode==null)
                    continue;
                else
                {
                    lineSubsectionCode.Add(orderinfo.lineSubsectionCode);
                    data.Add(orderinfo);
                }
                   
            }
            return new OrderRes(orderRes1.code,data,orderRes1.success,orderRes1.fail,orderRes1.mesg,orderRes1.Time);
            
        }

        public async Task<ResponseBase> UpdateProducingBomInfo()
        {
            var ProducingOrders = context.DC.Set<Order_Model>().Where(x=>x.MOrderStatus=="3").ToList();
            try
            {
                foreach (var order in ProducingOrders)
                {
                    await BOMSynchronousAsync(order.OrderCode, "TH13", _LineCode);  
                }
                return new ResponseBase(true, "更新完成");
            }
            catch(Exception ex)
            {
                return new ResponseBase(false, ex.Message);
            }
           
        }

        /// <summary>
        /// 排程状态变更
        /// </summary>
        /// <param name="order">新工单信息</param>
        /// <returns></returns>
        public async Task<bool> SysncScheduleStatus(Order_Model order)
        {
            string factoryCode = configuration["FactoryCode"];
            string mesIP = configuration["MESIP"];
            string mesPort = configuration["MESPORT"];

            SysncScheduleStatusRequest request= new SysncScheduleStatusRequest();
            request.scheduleCode = order.ScheduleCode;
            request.scheduleStateCode = order.MOrderStatus;
            SysncScheduleStatusResponse response = new SysncScheduleStatusResponse();
            
            //利用工厂编码，产线编码 调用工单排程信息查询接口
            try
            {
                string url = "http://" + mesIP + ":" + mesPort + configuration["GETCHILDLINE"];
                string psd = JsonConvert.SerializeObject(request);
                string value = await httpService.PostDataAsync(url, psd);
                response = JsonConvert.DeserializeObject<SysncScheduleStatusResponse>(value);
                if (response.code == "000000")
                {
                    return true;
                }
                return true;
            }
            catch(Exception ex)
            {
                return true;
            }
            
        }

        /// <summary>
        /// 排程状态变更请求类
        /// </summary>
        public class SysncScheduleStatusRequest
        {
            public string scheduleStateCode { get; set; }
            public string stationCode { get; set; }
            public string serviceId = "Base031_ScheduleOperate";
            public string factoryCode = "TH13";
            public string scheduleCode { get; set; }
        }

        public class SysncScheduleStatusResponse
        {
            public string code { get; set; }
            public interdata data { get; set; }
            public bool fail { get; set; }
            public string mesg { get; set; }
            public bool success { get; set; }
            public string time { get; set; }
        }
        public class interdata
        {
            public string code { get; set; }
            public string data { get; set; }
            public bool fail { get; set; }
            public string mesg { get; set; }
            public bool success { get; set; }
            public string time { get; set; }

        }

        /// <summary>
        /// 更改旧的生产工单状态，以便切换新工单
        /// </summary>
        /// <param name="linecode"></param>
        public void ChangeLastProduceOrderScheduleStatus(string linecode)
        {
            var lastProduceOrder = context.DC.Set<Order_Model>().Where(x => x.LineCode == _LineCode && x.MOrderStatus == "3").ToList();
            foreach (var order in lastProduceOrder) {
                order.MOrderStatus = "2";
            }
            context.DC.SaveChanges();
        }

        // 工单状态同步工厂MES
        public async Task<ResponseBase> SyncStatus(ParaOrderStatus para)
        {
            string factoryCode = configuration["FactoryCode"];
            string mesIP = configuration["MESIP"];
            string mesPort = configuration["MESPORT"];

            try
            {
                RPWresquest rPWresquest = new RPWresquest
                {
                    serviceId = "Product013_AlterScheduleStatus",
                    factoryCode = factoryCode,
                    lineCode = para.LineCode
                };
                rPWresquest.data = new List<RPWbodydata>();
                RPWbodydata rPWbodydata = new RPWbodydata();
                rPWbodydata.orderCode = para.orderCode;
                rPWbodydata.scheduleCode = para.scheduleCode;
                rPWbodydata.scheduleStateCode = para.scheduleStateCode;
                rPWresquest.data.Add(rPWbodydata);

                string url = "http://" + mesIP + ":" + mesPort + configuration["PRODUCTURL"];

                string post = JsonConvert.SerializeObject(rPWresquest);
                string value = await httpService.PostDataAsync(url, post);
                RPWResponse rPWResponse = JsonConvert.DeserializeObject<RPWResponse>(value);

                if (rPWResponse.code == "000000")
                {
                    return new ResponseBase(true, "同步成功");
                }
                else
                {
                    logger.LogInformation("工单状态上传失败：" + rPWResponse.mesg);
                    return new ResponseBase(false, "同步状态失败");
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new ResponseBase(false, "异常: " + ex.Message);
            }
        }


        // 修改当前工单排程状态
        public async Task<ResponseBase> UpdateStatusAsync(string orderCode, string scheduleCode, OrderStatusEnum orderStatus, string status)
        {
            try
            {
                Order_Model order = context.DC.Set<Order_Model>().SingleOrDefault(e => e.OrderCode == orderCode && e.ScheduleCode == scheduleCode);

                if (order == null)
                {
                    return new ResponseBase(false, "工单排程编码错误，当前无此工单排程");
                }

                if (order.Order_Status != orderStatus || order.MOrderStatus != status)
                {
                    //切换生产状态 需判断目前产线没有生产的工单排程
                    if (status == "3")
                    {
                        string lineCode = order.LineCode;
                        List<Order_Model> orders = context.DC.Set<Order_Model>().Where(e => e.LineCode == lineCode && e.MOrderStatus == "3").ToList();
                        //目前无生产排程
                        if (orders.Count() == 0)
                        {
                            order.Order_Status = orderStatus;
                            order.MOrderStatus = status;
                        }
                        else
                        {
                            return new ResponseBase(false, "修改状态失败，目前产线已有在生产工单");
                        }
                    }
                    else
                    {
                        order.Order_Status = orderStatus;
                        order.MOrderStatus = status;
                    }
                    await context.DC.SaveChangesAsync();
                }
                return new ResponseBase(true, "修改成功");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new ResponseBase(false, "异常：" + ex.Message);
            }
        }


        // 根据产线工位获取当前 在生产工单信息
        public MOrderAndSchedule FindByLineAndStation(string lineCode, string stationCode)
        {
            try
            {
                Order_Model order = context.DC.Set<Order_Model>().
                    SingleOrDefault(e => e.LineCode == lineCode && e.StationCode == stationCode && e.MOrderStatus == "3");
                if (order == null)
                {
                    //非首战工位，查询绑定关系表
                    return new MOrderAndSchedule(false, "OTHER", null, null);
                }
                else
                {
                    return new MOrderAndSchedule(true, "获取成功", order.OrderCode, order.ScheduleCode);
                }
            }
            catch (Exception ex)
            {
                return new MOrderAndSchedule(false, "异常: " + ex.Message, null, null);
            }

        }


        // 增加工单数量
        public async Task<ResponseBase> AddOrderNum(string orderCode, string scheduleCode)
        {
            try
            {
                Order_Model order = context.DC.Set<Order_Model>().SingleOrDefault(e => e.OrderCode == orderCode && e.ScheduleCode == scheduleCode);

                if (order == null)
                {
                    return new ResponseBase(false, "工单排程编码错误，当前无此工单排程");
                }

                order.Field4 = (int.Parse(order.Field4) + 1).ToString();

                //排程状态结束
                if (string.Compare(order.Field4, order.ScheduleQty) >= 0)
                {
                    var res = await UpdateStatusAsync(orderCode, scheduleCode, order.Order_Status, "6");
                    if (res.Success == true)
                    {
                        //同步工厂MES
                        //LineCode, string orderCode, string scheduleCode, string scheduleStateCode
                        ParaOrderStatus para = new ParaOrderStatus(order.Field5, order.OrderCode, order.ScheduleCode, order.MOrderStatus);
                        var res1 = await SyncStatus(para);
                        if (res1.Success == false)
                        {
                            return new ResponseBase(false, "增加工单数量失败: " + res1.Mesg);
                        }
                    }
                    else
                    {
                        return new ResponseBase(false, "增加工单数量失败: " + res.Mesg);
                    }
                }
                return new ResponseBase(true, "增加工单数量成功");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new ResponseBase(false, "异常: " + ex.Message);
            }
        }


        // 获取产线在生产工单
        public ResponseComBase<Order_Model> GetOrderInProduct(string lineCode, string sn)
        {
            try
            {
                // 子产线生产工单
                Order_Model order1 = context.DC.Set<Order_Model>()
                    .SingleOrDefault(e => e.MOrderStatus == "3" && e.LineCode == lineCode);
                if (order1 == null)
                {
                    return new ResponseComBase<Order_Model>() { Success = false, Mesg = "当前无在生产工单" };
                }
                else
                {
                    return new ResponseComBase<Order_Model>() { Success = true, Mesg = "success", Data = order1 };
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new ResponseComBase<Order_Model>() { Success = false, Mesg = "获取工单信息异常" };
            }

        }

        // 通过 工单排程 产线工序获取装配信息
        public async Task<List<ProductBOM>> GetAssemblyInfo(string orderCode, string scheduleCode, string lineCode, string operationCode)
        {
            return context.DC.Set<ProductBOM>().Where(e => e.OrderCode == orderCode && e.ScheduleNumber == scheduleCode && e.Assemblyline == lineCode && e.OperationCode == operationCode).ToList();
        }

        public ResponseComBase<Order_Model> GetOrderInProduct(string sn)
        {
            try
            {
                // var ordercode = context.DC.Set<TrayBindVSN>().SingleOrDefault(x => x.VSN == sn)?.OrderCode;

                TrayBindVSN orderInfo = context.DC.Set<TrayBindVSN>().SingleOrDefault(x => x.VSN == sn);

                if (orderInfo == null)
                {
                    return new ResponseComBase<Order_Model>() { Success = false, Mesg = "当前无在生产工单" };
                }
                else
                {

                    // 根据工单号带出关联工单信息；
                    Order_Model order = context.DC.Set<Order_Model>()
                        .SingleOrDefault(e => e.OrderCode == orderInfo.OrderCode && e.ScheduleCode == orderInfo.ScheduleCode);
                    if(order == null)
                    {
                        logger.LogInformation("获取工单信息失败： " + orderInfo.OrderCode + " " + orderInfo.ScheduleCode);
                        return new ResponseComBase<Order_Model>() { Success = false, Mesg = "获取工单信息失败" };
                    }
                    return new ResponseComBase<Order_Model>() { Success = true, Mesg = "success", Data = order };
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new ResponseComBase<Order_Model>() { Success = false, Mesg = "获取工单信息异常" };
            }

        }

        public async Task<string> BOMSynchronousAsync(string orderCode, string factoryCode, string lineCode)
        {
            BOMrequest bOMrequest = new BOMrequest();
            bOMrequest.orderCode = orderCode;
            bOMrequest.factoryCode = factoryCode;
            bOMrequest.lineCode = lineCode;
            bOMrequest.requestTime = DateTime.Now.ToString("yy-MM-dd HH:mm:ss");
            bOMrequest.updateTime = DateTime.Now.ToString("yy-MM-dd HH:mm:ss");

            var thisorderlineCode = context.DC.Set<Order_Model>().SingleOrDefault(x => x.OrderCode == orderCode)?.LineCode;

            //BomResponse bomResponse= new BomResponse();
            //bomResponse.data = new List<BomData>();
            //BomData bomData = new BomData();
            try
            {
                string psd = JsonConvert.SerializeObject(bOMrequest);
                logger.LogInformation(psd);
                string value = await httpService.PostDataAsync("http://"+mesIP+":"+mesPort+"/api/base/Base_Information", psd);
                logger.LogInformation("bomsync|"+value);   
                BomResponse BOMRes = JsonConvert.DeserializeObject<BomResponse>(value);

                for (int i = 0; i < BOMRes.data.Count; i++)
                {
                    ProductBOM mproductBOM = new ProductBOM();
                    List<ProductBOM> Pbom = context.DC.Set<ProductBOM>().Where(x => x.OrderCode == BOMRes.data[i].orderCode && x.AssemblyMaterialCode == BOMRes.data[i].assemblyMaterialCode&&x.OperationCode== BOMRes.data[i].operationCode).ToList();
                    if (Pbom.Count == 0)
                    {
                        mproductBOM.AddTime = BOMRes.data[i].addTime;
                        //BOMRes.data[i].assemblyConsumption = (Convert.ToInt16(BOMRes.data[i].assemblyConsumption)).ToString();
                        mproductBOM.AssemblyConsumption = BOMRes.data[i].assemblyConsumption.Substring(0, BOMRes.data[i].assemblyConsumption.IndexOf("."));
                        mproductBOM.AssemblyMaterialCode = BOMRes.data[i].assemblyMaterialCode;
                        mproductBOM.AssemblyMaterialId = BOMRes.data[i].assemblyMaterialId;
                        mproductBOM.AssemblyMaterialName = BOMRes.data[i].assemblyMaterialName;
                        if (BOMRes.data[i].operationCode == "2-OP3180" || BOMRes.data[i].operationCode == "2-OP4010")
                            mproductBOM.AssemblyMaterialRegex = "^DM-TG-+";
                        else
                            mproductBOM.AssemblyMaterialRegex = BOMRes.data[i].assemblyMaterialRegex;
                        mproductBOM.AssemblyMaterialVersion = BOMRes.data[i].assemblyMaterialVersion;
                        mproductBOM.AssemblyUnitCode = BOMRes.data[i].assemblyUnitCode;
                        mproductBOM.Assemblyline = thisorderlineCode;
                        mproductBOM.AutoMaterialDeduction = BOMRes.data[i].autoMaterialDeduction;
                        mproductBOM.EditTime = BOMRes.data[i].editTime;
                        mproductBOM.Field1 = BOMRes.data[i].field1;
                        mproductBOM.Field2 = BOMRes.data[i].field2;
                        mproductBOM.Field3 = BOMRes.data[i].field3;
                        mproductBOM.Field4 = BOMRes.data[i].field4;
                        mproductBOM.Field5 = BOMRes.data[i].field5;
                        mproductBOM.FactoryCode = BOMRes.data[i].factoryCode;
                        mproductBOM.IsDelete = BOMRes.data[i].isDelete;
                        mproductBOM.MaterialCode = BOMRes.data[i].materialCode;
                        mproductBOM.MaterialId = BOMRes.data[i].materialId;
                        mproductBOM.MaterialName = BOMRes.data[i].materialName;
                        mproductBOM.MaterialRegex = BOMRes.data[i].materialRegex;
                        mproductBOM.MaterialSort = BOMRes.data[i].materialSort;
                        mproductBOM.MaterialVersion = BOMRes.data[i].materialVersion;
                        mproductBOM.OperationCode = BOMRes.data[i].operationCode;
                        mproductBOM.OrderCode = BOMRes.data[i].orderCode;
                        mproductBOM.OrderId = BOMRes.data[i].orderId;
                        mproductBOM.OrderQty = BOMRes.data[i].orderQty;
                        mproductBOM.ProductBomId = BOMRes.data[i].productBomId;
                        mproductBOM.ReplaceMaterialList = BOMRes.data[i].replaceMaterialList.ToArray().ToString();
                        mproductBOM.Replaces = BOMRes.data[i].replaces;
                        mproductBOM.Retroactive = BOMRes.data[i].retroactive;
                        mproductBOM.RouteBomCode = BOMRes.data[i].routeBomCode;
                        mproductBOM.RouteBomName = BOMRes.data[i].routeBomName;
                        mproductBOM.RouteNumber = BOMRes.data[i].routeNumber;
                        mproductBOM.ScheduleNumber = BOMRes.data[i].scheduleNumber;
                        mproductBOM.ShipRegularCheck = BOMRes.data[i].shipRegularCheck;
                        mproductBOM.ShopOrderOperationMaterialId = BOMRes.data[i].shopOrderOperationMaterialId;
                        context.DC.Set<ProductBOM>().Add(mproductBOM);
                        context.DC.SaveChanges();
                    }
                    else
                    {
                        Pbom[0].AddTime = BOMRes.data[i].addTime;
                        //BOMRes.data[i].assemblyConsumption = (Convert.ToInt16(BOMRes.data[i].assemblyConsumption)).ToString();
                        Pbom[0].AssemblyConsumption = BOMRes.data[i].assemblyConsumption.Substring(0, BOMRes.data[i].assemblyConsumption.IndexOf("."));
                        Pbom[0].AssemblyMaterialCode = BOMRes.data[i].assemblyMaterialCode;
                        Pbom[0].AssemblyMaterialId = BOMRes.data[i].assemblyMaterialId;
                        Pbom[0].AssemblyMaterialName = BOMRes.data[i].assemblyMaterialName;
                        if (BOMRes.data[i].operationCode == "2-OP3180" || BOMRes.data[i].operationCode == "2-OP4010")
                            mproductBOM.AssemblyMaterialRegex = "^DM-TG-+";
                        else
                            mproductBOM.AssemblyMaterialRegex = BOMRes.data[i].assemblyMaterialRegex;
                        Pbom[0].AssemblyMaterialVersion = BOMRes.data[i].assemblyMaterialVersion;
                        Pbom[0].AssemblyUnitCode = BOMRes.data[i].assemblyUnitCode;
                        Pbom[0].Assemblyline = thisorderlineCode;
                        Pbom[0].AutoMaterialDeduction = BOMRes.data[i].autoMaterialDeduction;
                        Pbom[0].EditTime = BOMRes.data[i].editTime;
                        Pbom[0].Field1 = BOMRes.data[i].field1;
                        Pbom[0].Field2 = BOMRes.data[i].field2;
                        Pbom[0].Field3 = BOMRes.data[i].field3;
                        Pbom[0].Field4 = BOMRes.data[i].field4;
                        Pbom[0].Field5 = BOMRes.data[i].field5;
                        Pbom[0].FactoryCode = BOMRes.data[i].factoryCode;
                        Pbom[0].IsDelete = BOMRes.data[i].isDelete;
                        Pbom[0].MaterialCode = BOMRes.data[i].materialCode;
                        Pbom[0].MaterialId = BOMRes.data[i].materialId;
                        Pbom[0].MaterialName = BOMRes.data[i].materialName;
                        Pbom[0].MaterialRegex = BOMRes.data[i].materialRegex;
                        Pbom[0].MaterialSort = BOMRes.data[i].materialSort;
                        Pbom[0].MaterialVersion = BOMRes.data[i].materialVersion;
                        Pbom[0].OperationCode = BOMRes.data[i].operationCode;
                        Pbom[0].OrderCode = BOMRes.data[i].orderCode;
                        Pbom[0].OrderId = BOMRes.data[i].orderId;
                        Pbom[0].OrderQty = BOMRes.data[i].orderQty;
                        Pbom[0].ProductBomId = BOMRes.data[i].productBomId;
                        Pbom[0].ReplaceMaterialList = BOMRes.data[i].replaceMaterialList.ToArray().ToString();
                        Pbom[0].Replaces = BOMRes.data[i].replaces;
                        Pbom[0].Retroactive = BOMRes.data[i].retroactive;
                        Pbom[0].RouteBomCode = BOMRes.data[i].routeBomCode;
                        Pbom[0].RouteBomName = BOMRes.data[i].routeBomName;
                        Pbom[0].RouteNumber = BOMRes.data[i].routeNumber;
                        Pbom[0].ScheduleNumber = BOMRes.data[i].scheduleNumber;
                        Pbom[0].ShipRegularCheck = BOMRes.data[i].shipRegularCheck;
                        Pbom[0].ShopOrderOperationMaterialId = BOMRes.data[i].shopOrderOperationMaterialId;
                        context.DC.SaveChanges();
                    }
                }
                return "工单bom同步成功";
            }
            catch (Exception ex)
            {
                return "工单bom同步失败";
            }

        }

        /// <summary>
        /// 电驱工厂工单推送接口
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<DQBaseResponse.ApiResponse> DqUpdateOrderData(DqOrderRequest.ScheduleData orders)
        {
            DQBaseResponse.ApiResponse response = new DQBaseResponse.ApiResponse();
            try
            {
                DqOrder dqOrder = new DqOrder();
                foreach (var order in orders.data)
                {
                    //ChangeLastProduceOrderScheduleStatus(_LineCode);
                    dqOrder.factoryCode = order.factoryCode;
                    dqOrder.lineCode = order.lineCode;
                    dqOrder.lineName = order.lineName;
                    dqOrder.scheduleNumber = orders.scheduleNumber;
                    dqOrder.startTime = order.startTime;
                    dqOrder.endTime = order.endTime;
                    dqOrder.orderCode = order.orderCode;
                    dqOrder.orderQty = order.orderQty;
                    dqOrder.orderType = order.orderType;
                    dqOrder.orderStatus = order.orderStatus;
                    dqOrder.orderStateCode = order.orderStateCode;
                    dqOrder.orderStartTime = dqOrder.orderStartTime;
                    dqOrder.orderEndTime = dqOrder.orderEndTime;
                    dqOrder.scheduleCode = order.scheduleCode;
                    dqOrder.scheduleQty = order.scheduleQty;
                    dqOrder.scheduleStatus = order.scheduleStatus;
                    dqOrder.scheduleStateCode = order.scheduleStateCode;
                    dqOrder.scheduleStartTime = order.scheduleStartTime;
                    dqOrder.scheduleEndTime = order.scheduleEndTime;
                    dqOrder.productCode = order.productCode;
                    dqOrder.productName = order.productName;
                    dqOrder.productVersion = order.productVersion;
                    dqOrder.materialCode = order.materialCode;
                    dqOrder.materialName = order.materialName;
                    dqOrder.materialVersion = order.materialVersion;
                    dqOrder.routeCode = order.routeCode;
                    dqOrder.routeName = order.routeName;
                    dqOrder.routeVersion = order.routeVersion;
                    dqOrder.priority = order.priority;

                    context.DC.Set<DqOrder>().Add(dqOrder);
                    context.DC.SaveChanges();

                    Order_Model ordermodel =await MapToOrderModel(dqOrder);
                    await _stationServices.GetRouteFromFactory(order.lineCode, ordermodel);
                    await BOMSynchronousAsync(dqOrder.orderCode, dqOrder.factoryCode, dqOrder.lineCode);
                }
                response.success = true;
                response.code = "000000";
                response.data = "";
                response.mesg = "";
                response.time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                return response;
            }
            catch(Exception ex) 
            {
                response.success = false;
                response.code = "000001";
                response.data = "";
                response.mesg = ex.Message;
                response.time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                return response;
            }

        }

        public async Task<Order_Model> MapToOrderModel(DqOrder dqOrder)
        {
            var oldorder = context.DC.Set<Order_Model>().Where(x=>x.OrderCode == dqOrder.orderCode).FirstOrDefault();
            if(oldorder != null)
                return oldorder;
            Order_Model order = new Order_Model()
            {
                OrderCode = dqOrder.orderCode,

                MaterialCode = dqOrder.materialCode,
                MaterialVersion = dqOrder.materialVersion,
                OrderQty = dqOrder.orderQty,
                ScheduleCode = dqOrder.scheduleCode,
                ScheduleQty = dqOrder.scheduleQty,
                MaterialName = dqOrder.materialName,
                OrderType = dqOrder.orderType,
                //MaterialId = dqOrder.materialId,
                //ScheduleEditTime = dqOrder.scheduleEditTime,
                //ScheduleId = dqOrder.scheduleId,
                // ScheduleStationId = dqOrder.scheduleStationId,

                //排程状态（0-新建，1-下达，2-开线，3-生产，4-暂停，5-取消，6-完成）
                MOrderStatus = "2",
                //WorkshopCode = dqOrder.workshopCode,
                // WorkshopName = orderRes.data[i].workshopName,
                LineCode = _LineCode,
                LineName = dqOrder.lineName,
                StationCode = "2-OP1010-0",
                // StationName = orderRes.data[i].stationName,
                //EquipmentCode = orderRes.data[i].equipmentCode,
                StartTime = dqOrder.startTime.ToString("yyyy-MM-dd HH:mm:ss"),
                EndTime = dqOrder.endTime.ToString("yyyy-MM-dd HH:mm:ss"),
                FactoryCode = dqOrder.factoryCode,
                //Field1 = orderRes.data[i].field1,
                //Field2 = orderRes.data[i].field2,
                //Field3 = orderRes.data[i].field3,
                //Field4 = "0",
                // 保存工厂MES产线编码
                Field5 = dqOrder.lineCode
            };
            context.DC.Set<Order_Model>().Add(order);
            context.DC.SaveChanges();
            return order;
        }
    
        
    }
}
